<template>
  <div
    style="margin-top: 15px;min-height: 100%;"
    class="main-div"
  >
    <Spin v-show="isSpinShow" fix size="large" />

    <el-tabs v-model="activeName" >
      <el-tab-pane label="基本信息" name="form">
        <Card>
          <div slot="title">
        <span>
          <Button
            type="primary"
            style="margin-bottom: 2px;margin-right: 15px;"
            @click="action('startFlow')"
          >发起
          </Button>
          <Button
            type="primary"
            class="xr-btn--green"
            style="margin-bottom: 2px;margin-right: 15px;"
            @click="action('saveDraft')"
          >保存
          </Button>
          <Button
            type="primary"
            style="margin-bottom: 2px;margin-right: 15px;"
            @click="action('print')"
          >打印
          </Button>
          <Button type="primary" style="margin-bottom: 2px;margin-right: 15px;" @click="action('flowImage')">流程图
          </Button>
          <Button type="primary" style="margin-bottom: 2px;margin-right: 15px;" @click="go">
            <Icon type="md-close" />关闭
          </Button>
        </span>
          </div>
            <div v-if="jsonData.config!=null" class="container"   style=" overflow: auto;max-height: 550px">

              <fm-generate-form
                ref="generateForm"
                :data="jsonData"
                :remote="remoteFuncs"
                :value="editData"
                :remote-option="dynamicData"

              />

            </div>


        </Card>
      </el-tab-pane>
      <el-tab-pane label="附件" name="attachment">
        <el-form ref="attachmentForm" :model="attachmentForm" label-width="80px">
          <el-row class="table_form">
            <el-col :span="12">
              <el-form-item label="创建人" prop="createBy">
                <el-input v-model="attachmentForm.createBy" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间" prop="createTime">
                <el-input v-model="attachmentForm.createTime" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="内容" prop="changeContent">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="attachmentForm.changeContent">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="附件" prop="code">

                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :before-upload="uploadform"
                  :action="baseUploadURL"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="upFile"
                  :file-list="fileList"
                  :auto-upload="true">
                  <el-button type="primary">上传<i class="el-icon-upload el-icon--right"></i></el-button>

                  <div slot="tip" class="el-upload__tip"></div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" prop="code">

                <el-button size="small" type="success" @click="submitForm">保存</el-button>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </el-tab-pane>
    </el-tabs>

    <Modal
      :mask-closable="false"
      v-model="flowImage.show"
      title="流程图"
      width="85%"
      :transfer="false"
    >
      <iframe
        id="flowImageframe"
        width="100%"
        style="min-height: 600px"
        height="100%"
        frameborder="0"
        align="center"
        allowfullscreen="true"
        allow="autoplay"
        :src="flowImage.src"
      />
    </Modal>
  </div>

</template>

<script>
import {addAttachment, getStartBtn, renderStartForm, startDef, saveDraft } from '@/api/loadwfmodule'

export default {
  name: 'Task',
  components: {
  },

  data() {
    return {
      baseUploadURL: process.env.VUE_APP_BASE_BPM_API + "/a1bpmn/api/upload/drl",
      activeName: 'form',
      fileList: [],
      bpmTaskAttachment: [],
      attachmentForm: {
        createBy: '',
        id: '',
        createTime: '',
        procDefId: '',
        taskId: '',
        processInstanceId: '',
        changeContent: '',
        modelKey: '',
        file: [],
      },
      tableData: [],
      jsonData: {},
      editData: {},
      remoteFuncs: {},
      singleUserData: {},
      dynamicData: {},
      sysTypeEntity: {},
      isSpinShow: true,
      taskBtns: [],
      modelKey: '',
      tableHeight: 450,
      startForm: {
        defId: '',
        modelId: 0,
        typeTitle: '',
        formData: '',
        groupId: '',
        typeKey: '',
        draftId: ''
      },
      flowImage:
          {
            show: false,
            src: '',
            base: process.env.VUE_APP_BASE_BPM_API + '/view/def.html?fireHoverAction=true&modelId='
          }

    }
  },
  mount() {
    this.$nextTick(function() {
      // 获取传递的参数
      this.modelKey = this.$route.params.modelKey
      this.getData()
    })

    this.getData()
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
  },
  created: function() {
    // 获取传递的参数
    this.modelKey = this.$route.params.modelKey
    if (this.$route.params.modelKey) {
      this.attachmentForm.modelKey = this.modelKey
      this.attachmentForm = {
        createBy: '',
        id: '',
        createTime: '',
        procDefId: '',
        changeContent: '',
        modelKey: '',
        file: [],
      }

    }
    this.startForm.draftId = this.$route.params.draftId
    if(this.$route.params.formData){
      this.editData = JSON.parse(this.$route.params.formData)

    }
    this.getData()
  },
  methods: {
    /** 提交按钮 */
    submitForm() {
      this.$refs["attachmentForm"].validate(valid => {
        var formData = new FormData();//new一个formData事件
        for (var i = 0; i < this.attachmentForm.file.length; i++) {
          formData.append('files', this.attachmentForm.file[i]);
        }

        formData.append("procDefId", this.attachmentForm.procDefId);
        formData.append("changeContent", this.attachmentForm.changeContent);
        formData.append("modelKey", this.modelKey);
        if (this.attachmentForm.id) {
          formData.append("id", this.attachmentForm.id);
        }

        if (valid) {
          addAttachment(formData).then(response => {
            if (response.code == 0) {
              this.attachmentForm.id=response.msg
              this.startForm.attachmentId = this.attachmentForm.id;

              this.msgSuccess("操作成功");
            }

          });
        }
      });
    },
    handleRemove(file, fileList) {
      this.attachmentForm.file = fileList
    },
    handlePreview(file) {
    },
    uploadform: function (file) {
      if (!this.attachmentForm.file) {
        this.attachmentForm.file = []
      }
      this.attachmentForm.file.push(file)
    },
    /* 上传文件操作 */
    upFile(res, file) {
    },
    action: function(action) {
      if (typeof action === 'object') {
        this.alias = action.alias
      } else {
        this.alias = action
      }

      switch (this.alias) {
        case 'startFlow':// 启动
          this.startFlow()
          break
        case 'flowImage':
          this.flowImageAction()
          break
        case 'print':
          window.print()
          break
        case 'saveDraft':
          this.saveDraft()
          break
        default:
      }
    },
    flowImageAction: function() {
      this.flowImage.src = this.flowImage.base + this.startForm.modelId + '&t=' + new Date().getTime()
      this.flowImage.show = true
    },
    startFlow: function() {
      this.getFormData()
      const that = this
      setTimeout(function() {
        startDef(that.startForm).then((response) => {
          if (response.code == 0) {
            that.$message({message:'发起成功',type:'success',customClass:'zZindex'});

            that.go()
          }
        })
      }, 300)
    },

    async  saveDraft() {
      var formData = {}
      const get = () => {
        return new Promise(resolve => {
          formData = this.getFormData()
          resolve(formData)
        })
      }

      await get()
      const that = this
      var obj = JSON.parse(JSON.stringify(this.startForm))
      obj['formDataStr'] = obj['formData']
      obj['id'] = obj['draftId']
      delete (obj['formData'])

      saveDraft(obj).then((response) => {
        if (response.code == 0) {
          that.$message({"duration":'800',message:'保存成功',type:'success',customClass:'zZindex'});

          that.go()
        }
      })
    },
    getFormData: function() {
      this.$refs.generateForm.getData().then(data => {
        this.startForm.formData = JSON.stringify(data)
        return data
      }).catch(e => {
        console.log(e)
      })
    },
    go: function() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    },
    start: function(item) {
      this.$router.push({ name: 'handleHisTaskDetails', query: { t: new Date().getTime() }})
    },
    getData: function() {
      getStartBtn(this.modelKey).then((response) => {
        this.taskBtns = response.data
        this.startForm.defId = response.defId
        this.startForm.modelId = response.modelId

        if (response.bta) {
          this.attachmentForm.createBy = response.bta.createBy
          this.attachmentForm.createTime = response.bta.createTime
          this.attachmentForm.procDefId = response.bta.procDefId
          this.attachmentForm.userNo = response.bta.userNo
        }
        if (response.existBpmTaskAttachment) {
          this.attachmentForm.changeContent = response.existBpmTaskAttachment.changeContent
          this.attachmentForm.id = response.existBpmTaskAttachment.id
          this.startForm.attachmentId = this.attachmentForm.id;
          if (response.existBpmTaskAttachment.bpmTaskAttachmentDetailedList) {
            this.fileList = response.existBpmTaskAttachment.bpmTaskAttachmentDetailedList;
          }
        }else{
          //不存在数据
          this.startForm.attachmentId=""
          this.attachmentForm.id=""
          this.attachmentForm.changeContent=""
          this.fileList=[]
        }

        if(response.sysTypeEntity){
          this.startForm.typeTitle = response.sysTypeEntity.title
          this.startForm.groupId = response.sysTypeEntity.id
          this.startForm.typeKey = response.sysTypeEntity.typeKey
        }

        renderStartForm(this.startForm.defId).then((response) => {
          if (response.code == 0) {
            this.jsonData = JSON.parse(response.data)
            if (response.editData) {
              this.editData = JSON.parse(response.editData)
            }
          } else {
            this.go()
          }
        })

        this.isSpinShow = false
      })
    }

  }

}

</script>
<style lang="scss" scoped>
  .xr-btn--green {
    background-color: #389E0B;
    border-color: #389E0B;

    i {
      font-size: 13px;
      margin-right: 5px;
    }
  }

  .xr-btn--green:hover,
  .xr-btn--green.is-disabled,
  .xr-btn--green.is-disabled:hover,
  .xr-btn--green:focus {
    background: #4ca824;
    border-color: #4ca824;
    color: #FFFFFF;
  }
  .task-card {
    margin-top: 10px;
  }

  .item {
    display: block;
    width: 311px;
    float: left;
    margin-left: 20px;
    box-shadow: 0 0 20px 0 rgba(204, 207, 227, .45);
    margin-bottom: 10px;

  }

  .left{
    font-size: 16px;
    color: #575757;
  }

  img {
    width: 60px;
    height: 60px;
  }
  .container {
    height: auto !important;
    min-height: 450px;
  }
</style>
